package com.ingdan.contactdemo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class AddActivity extends Activity {
    private Button mBtSubmit;
    private TextView mEdName;
    private TextView mEdPhone;
    public static String TYPETAG = "type";
    public static String LINKNAME = "name";
    public static String LINKPHONE = "phone";
    public static String NO = "no";
    private String name;
    private String phone;
    private String StringNumnber;

    int type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        name = getIntent().getStringExtra(LINKNAME);
        phone = getIntent().getStringExtra(LINKPHONE);
        StringNumnber = getIntent().getStringExtra(NO);
        type = getIntent().getIntExtra(TYPETAG, 0);
        mEdName = (TextView) findViewById(R.id.ed_name);
        mEdPhone = (TextView) findViewById(R.id.ed_phone);
        mBtSubmit = (Button) findViewById(R.id.bt_submit);

        if (type == 1) {
            mEdName.setText(name);
            mEdName.setEnabled(false);
            mEdPhone.setText(phone);
            mBtSubmit.setText("修改");
        }


        mBtSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = mEdName.getText().toString();
                String phone = mEdPhone.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(AddActivity.this, "请输入姓名", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(AddActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d("AddActivity", "type:" + type);
                    if (type == 0) {

                        writeContact(name, phone);
                    } else {
                        Log.d("AddActivity", name + phone);
//                        changeContact(name, phone);
                        update(StringNumnber,phone);
                    }

                }
            }

        });
    }

    /**
     * 写入手机联系人
     */
    private void writeContact(String name, String phone) {
        //先查询要添加的号码是否已存在通讯录中, 不存在则添加. 存在则提示用户
        Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + phone);
        ContentResolver resolver = getContentResolver();
        //从raw_contact表中返回display_name
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data.DISPLAY_NAME}, null, null, null);
        if (cursor == null) {
            return;
        }

        if (cursor.moveToFirst()) {
            Log.i("nn", "name=" + cursor.getString(0));
            Toast.makeText(this, "存在相同号码", Toast.LENGTH_SHORT).show();
        } else {
            uri = Uri.parse("content://com.android.contacts/raw_contacts");
            ContentValues values = new ContentValues();
            long contact_id = ContentUris.parseId(resolver.insert(uri, values));
            //插入data表
            uri = Uri.parse("content://com.android.contacts/data");
            //add Name
            values.put("raw_contact_id", contact_id);
            values.put(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/name");
            values.put("data2", name);
            values.put("data1", name);
            resolver.insert(uri, values);
            values.clear();

            //add Phone
            values.put("raw_contact_id", contact_id);
            values.put(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/phone_v2");
            //手机
            values.put("data2", "2");
            values.put("data1", phone);
            resolver.insert(uri, values);
            values.clear();


            Toast.makeText(this, "插入号码成功", Toast.LENGTH_SHORT).show();
            mEdName.setText("");
            mEdPhone.setText("");
            finish();
        }
        cursor.close();
    }

    /**
     * 更改联系人
     */
    private void changeContact(String name, String phone) {

        //根据姓名求id
//        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri uri = Uri.parse("content://com.android.contacts/data");
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data._ID}, "display_name=?", new String[]{name}, null);
        if (cursor == null) {
            Toast.makeText(this, "错误", Toast.LENGTH_SHORT).show();
            return;

        }

        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);
            ContentValues values = new ContentValues();
            values.put("data1", phone);
            resolver.update(uri, values, "mimetype=? and raw_contact_id=?", new String[]{"vnd.android.cursor.item/phone_v2", id + ""});

        } else {
            Toast.makeText(this, "没有找到号码", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }


    // 更新联系人
    public void update(String rawRawContactId, String NewNumber)
    {

        Log.d("AddActivity", rawRawContactId + NewNumber);
        ContentValues values = new ContentValues();
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, NewNumber);
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        String Where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] WhereParams = new String[]{rawRawContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, };

        getContentResolver().update(ContactsContract.Data.CONTENT_URI, values, Where, WhereParams);
        Toast.makeText(this, "修改完成", Toast.LENGTH_SHORT).show();
    }

}
